<html lang="zh-CN">
<head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <style>
        .el-dialog__body {
            /*height: 30vh;*/
            overflow: auto;
        }

        #inventGroupManage.el-checkbox__input > .el-checkbox__inner {
            display: none;
        }

        #inventGroupManage.is-leaf + .el-checkbox .el-checkbox__inner {
            display: inline-block;
        }
        #inventGroupManage .table-wrap {
            height: 760px !important;
            overflow: auto;
        }
        @media (max-width: 1366px) {
            #inventGroupManage .table-wrap {
                height: 500px !important;
                overflow: auto;
            }
        }
    </style>
</head>
<body>
<div id="inventGroupManage" class="center_div" style="display:none;">
    <div class="searchForm" style="margin-top: 1%;margin-left: 1%">
        <template>
            编组：
            <el-input v-model="name" size="mini" style="    width: 10%"></el-input>
        </template>
        <el-button type="primary" size="mini" @click="query">查询</el-button>
        <el-button type="primary" size="mini" @click="add">添加</el-button>
    </div>
    <div class="table-wrap">
        <el-table
                :data="tableData"
                style="width:100%;text-align: center;border-left:1px solid #EBEBEB"
                header-cell-style="font-size:15px;text-align:center;color:#515A6E;padding:10px 0px 10px 0px !important;background:#F5F5F6;border:1px solid #EBEBEB;border-left:none"
                cell-style="font-size:13px;text-align:center;color:#606266;padding:5px 0px 5px 0px !important;border:1px solid #EBEBEB;border-top:none;border-left:none">
           <!-- <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>-->
            <el-table-column v-for="title in tableTitle" :prop="title.prop" :label="title.label">
            </el-table-column>
            <template v-if="buttons && buttons.length!==0">
                <el-table-column
                        class="align-right"
                        width="230px"
                        label="操作">
                    <template slot-scope="scope">
                        <el-button v-for="button in buttons"
                                   @click="operate(scope.row,button.href)" :type="button.type"
                                   class="el-button el-button--text el-button--medium">{{button.label}}
                        </el-button>
                    </template>
                </el-table-column>
            </template>
        </el-table>
        <el-pagination
                layout="prev, pager, next"
                @current-change="changePageNum"
                :current-page="pageNum"
                :page-size="pageSize"
                :total="total">
        </el-pagination>
    </div>
    <div>
        <el-dialog :title="title"
                   :visible.sync="showBox"
                   width="35%"
                   @close="closeDialog"
                   append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="mini">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="编组"  prop="name">
                            <el-input v-model="form.name"></el-input>
                        </el-form-item>
                    </el-col>
                   <!-- <el-col :span="12">
                        <el-form-item label="归属集团" :required="true" prop="fleetName">
                            <el-select v-model="form.fleetName" :placeholder="'请选择'" filterable>
                                <el-option :value="form.fleetName" style="height: auto">
                                    <el-tree
                                            :load="loadChildren"
                                            highlight-current
                                            lazy
                                            node-key="id"
                                            :props="chooseForm.defaultProps"
                                            :filter-node-method="filterNode"
                                            ref="tree"
                                            @node-click="loadData">
                                    </el-tree>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>-->
                    <el-col :span="12">
                        <el-form-item label="IP分机号码" prop="extNumber">
                            <el-select v-model="form.extNumber" placeholder="请选择">
                                <el-option
                                        v-for="item in extNumberOptions"
                                        :key="item.Sipnumber"
                                        :label="item.Sipnumber"
                                        :value="item.Sipnumber">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="22">
                        <el-form-item label="描述" prop="remark">
                            <el-input v-model="form.remark" type="textarea"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-form-item>
                        <el-button type="primary" @click="addInventGroup" v-show="showAdd">添加</el-button>
                        <el-button type="primary" @click="updateInventGroup" v-show="!showAdd">修改</el-button>
                        <el-button type="primary" @click="closeBox">取消</el-button>
                    </el-form-item>
                </el-row>
            </el-form>
        </el-dialog>
    </div>
    <el-dialog v-if="loadTree"
               :title="chooseForm.title"
               :visible.sync="chooseForm.seen"
               @close="closeTreeDialog"

               append-to-body>
        <div style="height: 400px">

            <div style="float:left;width:60%;height:90%">
                <div>
                    <div class="split-line">请选择</div>
                </div>
                <div style="height:99%;width:99%;margin-top:1%;background:white;overflow:auto">
                    <el-tree check-strictly
                             :load="loadChildren"
                             show-checkbox
                             highlight-current
                             lazy
                             node-key="id"
                             :props="chooseForm.defaultProps"
                             :filter-node-method="filterNode"
                             ref="tree"
                             @check-change="handleLeftCheckChange">
                        <span class="custom-tree-node" style="font-size: 14px" slot-scope="{ node, data }">
                            <span v-if="data.type===0"><img src="images/mapicon/tree_fleet.png" style="height: 15px;width: 15px;margin-right: 10px;vertical-align: middle">{{ node.label }}</span>
                            <span v-if="data.type===1"><img src="images/mapicon/tree_fleet.png" style="height: 15px;width: 15px;margin-right: 10px;vertical-align: middle">{{ node.label }}</span>
                            <span v-if="data.type===2"><img src="images/mapicon/tree_sub.png" style="height: 15px;width: 15px;margin-right: 10px;vertical-align: middle">{{ node.label }}</span>
                            <span v-if="data.type===3"><img src="images/mapicon/tree_user.png" style="height: 15px;width: 15px;margin-right: 10px;vertical-align: middle">{{ node.label }}</span>
                        </span>
                    </el-tree>
                </div>
            </div>

            <div style="float:right;width:40%;height:90%;background: ghostwhite;overflow: auto">
                <div>
                    <div class="split-line">已选择</div>
                </div>
                <el-row v-for="item in chooseForm.rightList" :key="item.id" style="padding: 3px">
                    <el-col :span="16" style="padding-top: 5px;font-size: 13px">
                                <span style="text-overflow:ellipsis">
                                   {{item.name}}
                                </span>
                    </el-col>
                    <el-col :span="5">
                        <el-button @click="deleteRightMember(item.id)"
                                   class="el-button el-button--text el-button--medium">删除
                        </el-button>
                    </el-col>
                </el-row>
            </div>

        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="chooseForm.seen = false">取 消</el-button>
            <el-button type="primary" @click="resModify">确 定</el-button>
        </div>
    </el-dialog>
</div>
</body>
<script>
    VueComponent.createInventGroupManage = function () {
        if (window.inventGroupManageVue) {
            return;
        }
        window.inventGroupManageVue = new Vue({
            el: "#inventGroupManage",
            data: {
                name: '',
                loadTree: true,
                tableTitle: [
                    {label: '编组', prop: 'name'},
                    {label: '分机号', prop: 'extNumber'},
                //    {label: '集团', prop: 'fleetName'},
                    {label: '描述', prop: 'remark'},
                ],
                rules: {
                    name: [
                        {required: true, message: '请输入虚拟组名称', trigger: 'blur'},
                        {min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur'}
                    ], extNumber: [
                        {required: true, message: '请选择分机号', trigger: 'blur'},
                    ], fleetName: [
                        {required: true, message: '请选择集团', trigger: 'blur'},
                    ],remark: [
                        {required: false, message: '请选择集团', trigger: 'blur'},
                        {min: 1, max: 128, message: '长度不能超过128个字符', trigger: 'blur'}
                    ],
                },
                tableData: [],
                memberTableTitle: [
                    {label: '成员', prop: 'subName'},
                    {label: '归属集团', prop: 'fleetName'},
                    {label: '编组', prop: 'groupName'},
                ],
                memberTableData: [],
                total: 0,
                pageNum: 1,
                pageSize: 15,
                buttons: [{label: "编辑", href: "update"}, {label: "删除", href: "delete"}, {
                    label: "成员管理",
                    href: "manage"
                }],

                extNumberOptions: [],

                showBox: false,
                showAdd: true,
                title: '',
                form: {
                    id: '',
                    name: '',
                    fleetName: '',
                    fleetId: '',
                    remark: '',
                    extNumber: '',
                },
                chooseForm: {
                    seen: false,
                    title: "成员管理",
                    leftList: [],
                    rightList: [],
                    type: 0, //0- 新增资源   1- 新增群组人员
                    groupId: 0,
                    defaultProps: {
                        label: 'name',
                        isLeaf: 'isLeaf'
                    },
                },
                groupId: '',
                type: 1,
            },
            mounted: function () {
                this.query();
            },
            methods: {

                closeDialog(){

                    this.$nextTick(function () {
                        this.$refs["form"].resetFields();
                    });
                },
                getExtNumber: function () {
                    var that = this;
                    that.loadindgExtnum = true;

                    axios.post('/scs/userManage/getExtNumber', {})
                        .then(function (res) {
                            if (res.status === 200) {
                                var data = res.data;
                                if (res.data.success) {
                                    that.extNumberOptions = data.obj.list;
                                } else {
                                    that.$message(res.msg);
                                }
                            } else {
                                this.$message(res.msg);
                            }
                            that.loadindgExtnum = false;

                        }.bind(this)).catch(function () {

                    }.bind(this));
                },
                closeTreeDialog(){
                    console.info("closeTreeDialog");
                    window.inventGroupManageVue.loadTree = false;
                    this.$nextTick(function () {
                        window.inventGroupManageVue.loadTree = true;
                    });

                },
                handleLeftCheckChange: function (data, checked, indeterminate) {
                    console.log(data, checked, indeterminate);
                    if (checked) {
                        var nodeObj = {};
                        nodeObj.id = data.id;
                        nodeObj.type = data.type;
                        nodeObj.userExtNumber = data.userExtNumber;
                        if (data.name.length > 5) {
                            nodeObj.name = data.name.substring(0, 5) + '...';
                        } else {
                            nodeObj.name = data.name;
                        }
                        var length = false;
                        for (var i = 0; i < this.chooseForm.rightList.length; i++) {
                            var id = this.chooseForm.rightList[i].id;
                            if (data.id === this.chooseForm.rightList[i].id) {
                                length = true;
                            }
                        }
                        if (!length) {
                            this.chooseForm.rightList.push(nodeObj);
                        }
                    } else {
                        for (var i = 0; i < this.chooseForm.rightList.length; i++) {
                            if (data.id === this.chooseForm.rightList[i].id) {
                                this.chooseForm.rightList.splice(i, 1);
                            }
                        }
                    }


                    for (var i = 0; i < this.chooseForm.rightList.length; i++) {
                        var node = this.$refs.tree.getNode(this.chooseForm.rightList[i].id);
                        if (node.checked === false) {
                            node.checked = true;
                        }
                    }
                },
                loadChildren: function (node, resolve) {
                    var that = this;
                    if (node.data) {
                        if (node.data.type === 2) {
                            var childNodes = [];
                            return resolve(childNodes);
                        } else {
                            that.getChild(node.data.id, node.data.type, resolve);
                        }
                    } else {
                        setTimeout(function () {
                            that.getChild(window.fleetId, 0, resolve);
                        }, 0);
                    }
                },
                getChild: function (id, type, resolve) {
                    if (this.chooseForm.seen === true) {
                        var jsonData = {
                            parentId: id,
                            type: type,
                            groupId: this.groupId
                        };
                        axios.post('/scs/fleetManage/getFleetAndSubAndUser', jsonData)
                            .then(function (res) {
                                res = res.data;
                                if (res.success) {

                                    var childNodes = [];
                                    if (res.obj && res.obj.length > 0) {
                                        for (var i = 0; i < res.obj.length; i++) {
                                            if (res.obj[i].type === 2 || res.obj[i].type === 3) {
                                                res.obj[i].isLeaf = true;
                                            }
                                        }
                                        childNodes = res.obj;
                                    } else {
                                        var node = window.inventGroupManageVue.$refs.tree.getNode(id);
                                        node.loading = false;
                                        return
                                    }
                                    resolve(childNodes);
                                    window.inventGroupManageVue.$nextTick(function () {
                                        for (var i = 0; i < window.inventGroupManageVue.chooseForm.rightList.length; i++) {

                                            var node = window.inventGroupManageVue.$refs.tree.getNode(window.inventGroupManageVue.chooseForm.rightList[i].id);
                                            if (node !== null) {
                                                if (node.checked === false) {
                                                    node.checked = true;
                                                }
                                            }
                                        }
                                    })
                                }
                            })
                    } else {
                        var jsonData = {
                            parentId: id,
                            type: type
                        };
                        axios.post('/scs/fleetManage/getFleet', jsonData)
                            .then(function (res) {
                                res = res.data;
                                if (res.success) {
                                    var childNodes = [];
                                    if (res.obj) {
                                        childNodes = res.obj;
                                    }
                                    resolve(childNodes);
                                }
                            })
                            .catch(function (error) {
                                console.log(error);
                            });
                    }

                },
                filterNode: function (value, data) {
                    if (!value)
                        return true;
                    else
                        return data.name.indexOf(value) !== -1;
                },
                loadData: function (node) {
                    this.form.fleetName = node.name;
                    this.form.fleetId = node.id;
                },

                deleteRightMember: function (id) {
                    for (var i = 0; i < this.chooseForm.rightList.length; i++) {
                        if (id === this.chooseForm.rightList[i].id) {
                            this.chooseForm.rightList.splice(i, 1);
                            var node = this.$refs.tree.getNode(id);
                            if (node !== null) {
                                node.checked = false;

                            }
                        }
                    }
                },
                refreshNodeBy: function (id) {
                    var node = this.$refs.tree.getNode(id);
                    node.loaded = false;
                    node.expand();
                },
                resModify: function () {
                    console.info("resModify");
                    var members = [];
                    for (var i = 0; i < this.chooseForm.rightList.length; i++) {
                        var memberObj = new Object();
                        memberObj.subId = this.chooseForm.rightList[i].id;
                        //暂时不支持添加调度员
                        memberObj.type = this.chooseForm.rightList[i].type;
                        memberObj.userExtNumber = this.chooseForm.rightList[i].userExtNumber;
                        members[i] = memberObj;
                    }
                    var condition = {
                        members: members,
                        groupId: this.groupId

                    };
                    var that = this;
                    axios.post('/scs/inventGroupManage/addInventGroupMember', condition)
                        .then(function (res) {
                            var res = res.data;
                            if (res.success) {
                                that.$message('添加成功');
                                that.chooseForm.seen = false;
                            } else {
                                that.$message('添加失败');
                            }
                        })
                        .catch(function (err) {
                            console.log(err);
                        });

                },

                query: function () {
                    var data = {
                        name: this.name || '',
                        pageNum: this.pageNum,
                        fleetId: window.fleetId,
                        pageSize: this.pageSize
                    };
                    axios.post('/scs/inventGroupManage/getInventGroup', data)
                        .then(function (res) {
                            if (res.status === 200) {
                                var data = res.data;
                                if (res.data.success) {
                                    this.tableData = data.obj.list;
                                    this.total = data.obj.total;
                                } else {
                                    this.$message('查询失败');
                                }
                            } else {
                                this.$message('查询失败');
                            }
                        }.bind(this)).catch(function () {

                    }.bind(this));
                },
                getMemberTableData: function (id) {
                    console.info("getMemberTableData");
                    var that = this;
                    axios.post('/scs/inventGroupManage/getMemberTableData', {groupId: id})
                        .then(function (res) {
                            if (res.status === 200) {
                                var data = res.data;
                                if (res.data.success) {
                                    that.chooseForm.rightList = [];
                                    for (var i = 0; i < res.data.obj.list.length; i++) {
                                        var item = new Object();
                                        item.userExtNumber = res.data.obj.list[i].userExtNumber;
                                        item.subId = res.data.obj.list[i].subId;
                                        item.id = res.data.obj.list[i].subId;
                                        item.type = res.data.obj.list[i].type;
                                        item.name = res.data.obj.list[i].subName;
                                        that.chooseForm.rightList[i] = item;
                                    }
                                    that.showDialog();
                                } else {
                                    this.$message('');
                                }
                            } else {
                                this.$message('');
                            }
                        }.bind(this)).catch(function () {

                    }.bind(this));
                },
                add: function () {
                    var that = this;
                    that.getExtNumber();
                    that.showBox = true;
                    that.showAdd = true;
                    that.title = "添加";
                },
                addInventGroup: function () {
                    var validate = false;
                    this.$refs["form"].validate((valid) => {
                        if (valid) {
                            validate = true;
                        } else {
                            console.log('error submit!!');
                            validate = false;
                            return false;
                        }
                    });
                    if (validate === false) {
                        return;
                    }
                    var that = this;
                    var data = {
                        name: this.form.name,
                       // fleetId: this.form.fleetId,
                        fleetId: window.fleetId,
                        remark: this.form.remark,
                        extNumber: that.form.extNumber,
                    };
                    axios.post('/scs/inventGroupManage/addInventGroup', data)
                        .then(function (res) {
                            var res = res.data;
                            if (res.success) {
                                that.closeBox();
                                that.$message('添加成功');
                                that.query();

                            } else {
                                that.$message('添加失败');
                            }
                        })
                        .catch(function (err) {
                            console.log(err);
                        });
                },
                updateInventGroup: function () {
                    var validate = false;
                    this.$refs["form"].validate((valid) => {
                        if (valid) {
                            validate = true;
                        } else {
                            console.log('error submit!!');
                            validate = false;
                            return false;
                        }
                    });
                    if (validate === false) {
                        return;
                    }
                    var that = this;
                    var data = {
                        id: that.form.id,
                        name: this.form.name,
                       // fleetId: this.form.fleetId,
                        fleetId: window.fleetId,
                        remark: this.form.remark,
                        extNumber: this.form.extNumber
                    };
                    axios.post('/scs/inventGroupManage/updateInventGroup', data)
                        .then(function (res) {
                            var res = res.data;
                            if (res.success) {
                                that.closeBox();
                                that.$message('编辑成功');
                                that.query();

                            } else {
                                that.$message('编辑失败');
                            }
                        })
                        .catch(function (err) {
                            console.log(err);
                        });
                },
                closeBox: function () {
                    this.showAdd = false;
                    this.showBox = false;
                    this.chooseForm.seen = false;
                },
                showDialog: function () {

                    this.chooseForm.seen = true;
                },
                operate: function (row, href) {
                    var that = this;
                    if (href.indexOf('update') !== -1) {
                        that.getExtNumber();
                        that.showBox = true;
                        that.showAdd = false;

                        that.title = "编辑";
                        that.form.id = row.id;
                        that.form.name = row.name;
                      //  that.form.fleetName = row.fleetName;
                        that.form.fleetId = row.fleetId;
                        that.form.remark = row.remark;
                        that.form.extNumber = row.extNumber;

                    } else if (href.indexOf('delete') !== -1) {
                        this.$confirm('是否确定删除', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            axios.post('/scs/inventGroupManage/deleteInventGroup', {id: row.id})
                                .then(function (res) {
                                    var res = res.data;
                                    if (res.success) {
                                        that.$message('删除成功');
                                        //此时已经实现删除操作，所以total的值需要减1，Math.ceil是向上取整，保证始终大于等于1
                                        const totalPage = Math.ceil((that.total - 1) / that.pageSize);
                                        //记住删除最后一条数据时当前码是最后一页
                                        const tempPageNum = that.pageNum > totalPage ? totalPage : that.pageNum;
                                        //实现跳转
                                        that.pageNum = tempPageNum < 1 ? 1 : tempPageNum;
                                        that.query();
                                    }
                                })
                                .catch(function (err) {
                                    console.log(err);
                                });
                        });
                    } else {
                        that.title = "成员管理";
                        that.groupId = row.id;
                        that.getMemberTableData(row.id);
                    }
                },
                deleteInventGroupMember: function (row) {
                    var that = this;
                    axios.post('/scs/inventGroupManage/deleteInventGroupMember', {
                        subId: row.subId,
                        groupId: row.groupId
                    })
                        .then(function (res) {
                            var res = res.data;
                            if (res.success) {
                                that.$message('删除成功');
                                that.getMemberTableData(row.groupId);
                                that.refreshNodeBy(window.fleetId);
                            }
                        })
                        .catch(function (err) {
                            console.log(err);
                        });
                },
                changePageNum: function (val) {
                    this.pageNum = val;
                    this.query();
                },
            }
        });
    }
</script>
</html>
